package com.hanthink.quartz.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.core.text.Convert;
import com.hanthink.common.utils.DateUtils;
import com.hanthink.system.domain.EmployeeWechat;
import com.hanthink.system.domain.logistics.ProductionDeliveryPlan;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.pc.EmJobItem;
import com.hanthink.system.domain.repair.RepairRecordInfo;
import com.hanthink.system.domain.repair.RequestInfo;
import com.hanthink.system.mapper.*;
import com.hanthink.system.mapper.logistics.ProductionDeliveryPlanMapper;
import com.hanthink.system.mapper.repair.RequestMapper;
import com.hanthink.system.service.pc.IEmEquipService;
import com.hanthink.system.service.pc.IEmJobItemService;
import com.hanthink.system.service.pc.IEmTaskService;
import com.hanthink.system.service.repair.IRepairRecordInfoService;
import com.hanthink.system.service.repair.IResquestInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.core.domain.entity.SysDictData;
import com.hanthink.common.core.domain.entity.SysRole;
import com.hanthink.common.core.domain.entity.SysUser;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.common.utils.StringUtils;
import com.hanthink.common.utils.jpush.JpushUtils;
import com.hanthink.quartz.domain.CallRecordInfoStic;
import com.hanthink.quartz.domain.EmEquipOperLog;
import com.hanthink.quartz.domain.EmItemFileInfo;
import com.hanthink.quartz.domain.EmPlanInfo;
import com.hanthink.quartz.domain.EquipStatusLog;
import com.hanthink.quartz.domain.EquipTaskItemInfo;
import com.hanthink.quartz.domain.MsgInfo;
import com.hanthink.quartz.domain.ReportTask;
import com.hanthink.quartz.domain.SiteTask;
import com.hanthink.quartz.domain.TaskInfo;
import com.hanthink.quartz.domain.TaskItemInfo;
import com.hanthink.quartz.domain.TaskSelectInfo;
import com.hanthink.quartz.mapper.CallRecordInfoMapper;
import com.hanthink.quartz.mapper.MsgMapper;
import com.hanthink.quartz.mapper.SysJobMapper;
import com.hanthink.quartz.mapper.TaskMapper;
import com.hanthink.quartz.mapper.TaskMsgMapper;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.pc.EmOutgoingQuality;
import com.hanthink.system.domain.pc.EmTask;
import com.hanthink.system.domain.user.UserClockInLog;
import com.hanthink.system.mapper.equipment.EmOutgoingQualityMapper;
import com.hanthink.system.mapper.repair.RepairPlanMapper;
import com.hanthink.system.mapper.repair.RepairTaskMapper;
import com.hanthink.system.domain.repair.RepairPlan;

import cn.jpush.api.push.PushResult;

/**
 * @author Administrator
 * <p>
 * 定时任务
 */
@Slf4j
@Component("jobTask")
public class JobTask {

    @Autowired
    private IEmTaskService taskService;

    @Autowired
    private MsgMapper msgMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private SysSerialNumberMapper sysSerialNumberMapper;

    @Autowired
    private TaskMsgMapper taskMsgMapper;

    @Autowired
    private SysJobMapper sysJobMapper;

    @Autowired
    private CallRecordInfoMapper callRecordInfoMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private IEmJobItemService emJobItemService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private EmTaskMapper emTaskMapper;


    @Autowired
    private RequestMapper requestMapper;


    @Autowired
    private EmOutgoingQualityMapper emOutgoingQualityMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private EmployeeWechatMapper employeeWechatserMapper;

    @Autowired
    private ProductionDeliveryPlanMapper productionDeliveryPlanMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IRepairRecordInfoService repairRecordInfoService;

    @Autowired
    private IResquestInfoService resquestInfoService;

    @Autowired
    private IEmEquipService emEqualTo;

    @Autowired
    private RepairPlanMapper repairPlanMapper;
    @Autowired
    private RepairTaskMapper repairTaskMapper;
    // 消息推送 flag
    private boolean pushMsgFlag = true;

    // 更新设备 flag
    private boolean updateEquipmentFlag = true;

    // 记录设备状态Flag
    private boolean insertEquipmentStatusFlag = true;

    // 超时响应消息生成 flag
    private boolean overTimeMsgFlag = true;

    // 计划任务生成 flag
    private boolean createPlanAndTaskFlag = true;

    // 任务完成统计 flag
    private boolean sumRepairAndTaskFlag = true;

    // 更新用户打卡状态 flag
    private boolean updateUserClockInStatusFlag = true;

    // 被动检查任务抽取 flag
    private boolean taskExtractFlag = true;


    // 问题65  被动抽查提醒 flag
    private boolean taskRemindFlag = true;

    private boolean repairPlanTaskFlag = true;

    private boolean taskExtractFlagQB = true;

    private SendWeChatMessage weChat = null;

    JpushUtils jpushUtils = new JpushUtils();
    Map<String, String> map = new HashedMap<>();
    String[] alias = new String[1];
    PushResult pushResult;

    //当前执行 计划
    private EmPlanInfo planTaskInfoExecute = null;

    /**
     * 推送消息
     */
    public void pushMsg() {
        try {
            if (!pushMsgFlag) {
                // 等待上次程序执行完毕
                return;
            }
            pushMsgFlag = false;
            List<MsgInfo> msgInfos = msgMapper.queryWaitPushMessage();
            if (msgInfos.size() > 0) {
                for (MsgInfo msgInfo : msgInfos) {
                    // 极光推送
                    //jpushMsg(msgInfo);
                    if (StringUtils.isEmpty(msgInfo.getWechatCode()) && !"@all".equals(msgInfo.getNotingUser())) {
                        // 当用户微信账户为空时，直接更新消息推送状态
                        msgMapper.updateMsgPushStatus(msgInfo);
                        continue;
                    }
                    // 推送消息至企业微信
                    if (weChat == null) {
                        weChat = new SendWeChatMessage();
                    }
                    if (StringUtils.isNotEmpty(msgInfo.getNotingUser()) && "@all".equals(msgInfo.getNotingUser())) {
                        // 获取机器人标签信息
                        String robotUrl = null;
                        SysDictData dictData = new SysDictData();
                        dictData.setDictType("robotUrl");
                        dictData.setDictLabel(msgInfo.getSiteName());
                        List<SysDictData> list = dictDataMapper.selectDictDataList(dictData);
                        if (list.size() > 0) {
                            robotUrl = list.get(0).getDictValue();
                            weChat.sendWeChatMessageToAll(msgInfo.getNewsDesc(), msgInfo.getNewsType(), robotUrl);
                        }
                    } else {
                        weChat.sendWeChatMessage(msgInfo.getWechatCode(), "1", "", msgInfo.getNewsDesc(), "0",
                                msgInfo.getNewsType());
                    }
                    // 更新推送状态
                    msgMapper.updateMsgPushStatus(msgInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            pushMsgFlag = true;
        }
    }


    public void taskExtractQB() {
        try {
            if (!taskExtractFlagQB) {
                // 等待上次程序执行完毕
                return;
            }
            taskExtractFlagQB = false;

            List<String> listss = new ArrayList<String>();

            //塑胶
            List<String> sjList = sysDeptMapper.selectDirectSubDeptById(Convert.toLong(238))
                    .stream().map(dept -> String.valueOf(dept.getDeptId())).collect(Collectors.toList());


            //三片
            List<String> spList = sysDeptMapper.selectDirectSubDeptById(Convert.toLong(270))
                    .stream().map(dept -> String.valueOf(dept.getDeptId())).collect(Collectors.toList());


            listss.addAll(sjList);
            //listss.addAll(spList);


            //问题66
            Integer monthEndNum = DateUtils.monthEndNum();


            List<SysUser> userList1 = userMapper.selectUserByRoleIdNew(Convert.toLong(191));

            //工作任务管理系统
            List<SysUser> userList2 = userMapper.selectUserByRoleIdNew(Convert.toLong(380));//380
            //LPA
//            List<SysUser> userList2 = userMapper.selectUserByRoleIdNew(Convert.toLong(508));//380

            SysRole sysRole191 = sysRoleMapper.selectRoleById(Convert.toLong(191));

            //工作任务管理系统
            SysRole sysRole380 = sysRoleMapper.selectRoleById(Convert.toLong(380));

            //LPA
//            SysRole sysRole380 = sysRoleMapper.selectRoleById(Convert.toLong(508));

            for (String s : listss) {

                //问题66  如果是塑胶事业部且当月剩余天数小于3天
                if (sjList.contains(s) && monthEndNum < 3) {
                    continue;
                }
                EmTask emTask = new EmTask();
                //塑胶
                if (sjList.contains(s)) {
                    emTask.setHangameKey(238 + "");
                } else {
                    emTask.setHangameKey(270 + "");
                }
                emTask.setStatus("2");
                Date[] date = DateUtils.getShiftDateQC();
                emTask.setStartTime(date[0]);
                emTask.setEndTime(date[1]);
                emTask.setSiteKey(s);

//                //这里不能写死
//                emTask.setTaskNum(Convert.toLong(10));

                SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
                Date dates = new Date();
                String batchno = s + format.format(dates) + "01" + "B";
                emTask.setBatchno(batchno);

                List<SysUser> userListall = new ArrayList<>();
                userListall.addAll(userList1);
                userListall.addAll(userList2);

                for (SysUser useriotem : userListall) {
                    if (!s.equals(useriotem.getParentid())) {
                        continue;
                    }
                    if (userList1.contains(useriotem)) {
                        emTask.setTaskNum(sysRole191.getRatio());
                    }

                    if (userList2.contains(useriotem)) {
                        emTask.setTaskNum(sysRole380.getRatio());
                    }
                    List<EmTask> taskList = taskService.selectRandomEmTaskListQC(emTask);

                    if (taskList.size() > 0) {
                        EmOutgoingQuality emOutgoingQuality = new EmOutgoingQuality();
                        emOutgoingQuality.setBatchNo(batchno);
                        emOutgoingQuality.setBatchNum(emTask.getTaskNum());
                        emOutgoingQuality.setType("1");
                        emOutgoingQuality.setUserId(useriotem.getUserId());
                        emOutgoingQuality.setIsFinished("0");
                        for (EmTask task : taskList) {
                            emOutgoingQuality.setHangameKey(task.getHangameKey());
                            emOutgoingQuality.setSiteKey(task.getSiteKey());
                            emOutgoingQuality.setTaskId(task.getId());
                            emOutgoingQualityMapper.insertEmOutgoingQuality(emOutgoingQuality);
                        }
                    }
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            taskExtractFlagQB = true;
        }
    }


    /**
     * 维修计划任务
     */
    public void createRepairPlanAndTask() {
        try {
            if (!repairPlanTaskFlag) {
                // 等待上次程序执行完毕
                return;
            }
            repairPlanTaskFlag = false;
            //新增维修计划
            List<RepairPlan> repairPlanList = repairPlanMapper.queryRepairPlanList();
            for (RepairPlan r : repairPlanList) {
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(r.getNextExecuteTime());
                Date nextExecuteTime = rightNow.getTime();
                // 将Date转换为String
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String strNextExecuteTime = dateFormat.format(nextExecuteTime).substring(0, 16);

                Calendar currentDayTime = Calendar.getInstance();
                currentDayTime.setTime(new Date());
                Date currentTime = currentDayTime.getTime();
                // 将Date转换为String
                SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String strCurrentTime = dateFormat1.format(currentTime).substring(0, 16);
                ;

                if (strNextExecuteTime.equals(strCurrentTime)) {
                    Map<String, Object> repairPlanParams = new HashMap<>();
                    repairPlanParams.put("id", r.getId());
                    repairPlanParams.put("equipno", r.getEquipno());
                    repairPlanParams.put("equipname", r.getEquipname());
                    repairPlanParams.put("hangameKey", r.getHangameKey());
                    repairPlanParams.put("siteKey", r.getSiteKey());
                    repairPlanParams.put("changeparts", r.getChangeparts());
                    repairPlanParams.put("cycle", r.getCycle());
                    repairPlanParams.put("isused", 0);
                    repairPlanParams.put("status", r.getStatus());
                    repairPlanParams.put("reason", r.getReason());
                    repairPlanParams.put("troublecontent", r.getTroublecontent());
                    repairPlanParams.put("nextExecuteTime", r.getNextExecuteTime());
                    repairTaskMapper.insertNewTask(repairPlanParams);
                    int ee = Integer.parseInt(r.getCycle().trim());
                    currentDayTime.add(Calendar.HOUR, ee);
                    Date newNextExecuteTime = currentDayTime.getTime();
                    Map<String, Object> params = new HashMap<>();
                    params.put("id", r.getId());
                    params.put("nextExecuteTime", newNextExecuteTime);
                    repairPlanMapper.updateNextExecuteTime(params);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            repairPlanTaskFlag = true;
        }
    }


    public void taskExtractQBB() {
        try {
            if (!taskExtractFlagQB) {
                // 等待上次程序执行完毕
                return;
            }
            taskExtractFlagQB = false;

            List<String> listss = new ArrayList<String>();

            //塑胶
            List<String> sjList = sysDeptMapper.selectDirectSubDeptById(Convert.toLong(238))
                    .stream().map(dept -> String.valueOf(dept.getDeptId())).collect(Collectors.toList());


            //三片
            List<String> spList = sysDeptMapper.selectDirectSubDeptById(Convert.toLong(270))
                    .stream().map(dept -> String.valueOf(dept.getDeptId())).collect(Collectors.toList());


//            listss.addAll(sjList);
            listss.addAll(spList);


            //问题66
            Integer monthEndNum = DateUtils.monthEndNum();


            List<SysUser> userList1 = userMapper.selectUserByRoleIdNew(Convert.toLong(191));

            //工作任务管理系统
//            List<SysUser> userList2 = userMapper.selectUserByRoleIdNew(Convert.toLong(380));//380
            //LPA
            List<SysUser> userList2 = userMapper.selectUserByRoleIdNew(Convert.toLong(508));//380

            SysRole sysRole191 = sysRoleMapper.selectRoleById(Convert.toLong(191));

            //工作任务管理系统
            SysRole sysRole380 = sysRoleMapper.selectRoleById(Convert.toLong(380));

            //LPA
//            SysRole sysRole380 = sysRoleMapper.selectRoleById(Convert.toLong(508));

            for (String s : listss) {

                //问题66  如果是塑胶事业部且当月剩余天数小于3天
                if (sjList.contains(s) && monthEndNum < 3) {
                    continue;
                }
                EmTask emTask = new EmTask();
                //塑胶
                if (sjList.contains(s)) {
                    emTask.setHangameKey(238 + "");
                } else {
                    emTask.setHangameKey(270 + "");
                }
                emTask.setStatus("2");
                Date[] date = DateUtils.getShiftDateQC();
                emTask.setStartTime(date[0]);
                emTask.setEndTime(date[1]);
                emTask.setSiteKey(s);

//                //这里不能写死
//                emTask.setTaskNum(Convert.toLong(10));

                SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
                Date dates = new Date();
                String batchno = s + format.format(dates) + "01" + "B";
                emTask.setBatchno(batchno);

                List<SysUser> userListall = new ArrayList<>();
                userListall.addAll(userList1);
                userListall.addAll(userList2);

                for (SysUser useriotem : userListall) {
                    if (!s.equals(useriotem.getParentid())) {
                        continue;
                    }
                    if (userList1.contains(useriotem)) {
                        emTask.setTaskNum(sysRole191.getRatio());
                    }

                    if (userList2.contains(useriotem)) {
                        emTask.setTaskNum(sysRole380.getRatio());
                    }
                    List<EmTask> taskList = taskService.selectRandomEmTaskListQC(emTask);

                    if (taskList.size() > 0) {
                        EmOutgoingQuality emOutgoingQuality = new EmOutgoingQuality();
                        emOutgoingQuality.setBatchNo(batchno);
                        emOutgoingQuality.setBatchNum(emTask.getTaskNum());
                        emOutgoingQuality.setType("1");
                        emOutgoingQuality.setUserId(useriotem.getUserId());
                        emOutgoingQuality.setIsFinished("0");
                        for (EmTask task : taskList) {
                            emOutgoingQuality.setHangameKey(task.getHangameKey());
                            emOutgoingQuality.setSiteKey(task.getSiteKey());
                            emOutgoingQuality.setTaskId(task.getId());
                            emOutgoingQualityMapper.insertEmOutgoingQuality(emOutgoingQuality);
                        }
                    }
                }

            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            taskExtractFlagQB = true;
        }
    }

    /**
     * 被动任务抽取
     */
    public void taskExtract() {
        try {
            if (!taskExtractFlag) {
                // 等待上次程序执行完毕
                return;
            }
            taskExtractFlag = false;
            // 查询需要抽取任务的角色
            List<SysRole> roleList = sysRoleMapper.selectNeedExtractRoleList();
            if (roleList.size() > 0) {
                for (SysRole sysRole : roleList) {
                    // 获取角色对应的用户
                    List<SysUser> userList = sysUserMapper.selectUserByRoleId(sysRole.getRoleId());
                    if (userList.size() > 0) {
                        // 查询时间范围获取
                        if (sysRole.getNextTime() == null) {
                            sysRole.setNextTime(new Date());
                        }
                        Calendar startTime = Calendar.getInstance();
                        startTime.setTime(sysRole.getNextTime());
                        startTime.add(Calendar.HOUR, -sysRole.getCycle().intValue());
                        sysRole.setLastTime(startTime.getTime());

                        EmTask emTask = new EmTask();
                        emTask.setStatus("2");
                        for (SysUser sysUser : userList) {
                            Long site = sysUser.getSite();
                            if (site == null || site == 0) {
                                continue;
                            }

                            emTask.setSiteKey(site.toString());
                            emTask.setStartTime(sysRole.getLastTime());
                            emTask.setEndTime(sysRole.getNextTime());
                            // 时间
                            int countNum = emTaskMapper.selectTaskCount(emTask);
                            if (countNum == 0)
                                continue;
                            if (sysRole.getRatio().intValue() >= countNum) {
                                emTask.setTaskNum(Long.valueOf(countNum));
                            } else {
                                emTask.setTaskNum(sysRole.getRatio());
                            }
//							int extractNum = (int) Math.ceil(countNum * (sysRole.getRatio().intValue() / 100.00));
//							emTask.setTaskNum(Long.valueOf(extractNum));
                            List<EmTask> taskList = emTaskMapper.selectRandomEmTaskList(emTask);
                            if (taskList.size() > 0) {
                                EmOutgoingQuality emOutgoingQuality = new EmOutgoingQuality();
                                emOutgoingQuality.setBatchNo(UUID.randomUUID().toString());
                                emOutgoingQuality.setBatchNum(Long.valueOf(emTask.getTaskNum()));
                                emOutgoingQuality.setType("1");
                                emOutgoingQuality.setUserId(sysUser.getUserId());
                                emOutgoingQuality.setIsFinished("0");
                                for (EmTask task : taskList) {
                                    emOutgoingQuality.setHangameKey(task.getHangameKey());
                                    emOutgoingQuality.setSiteKey(task.getSiteKey());
                                    emOutgoingQuality.setTaskId(task.getId());
                                    emOutgoingQualityMapper.insertEmOutgoingQuality(emOutgoingQuality);
                                }
                            }

                        }
                    }
                    sysRole.setLastTime(sysRole.getNextTime());
                    Calendar endTime = Calendar.getInstance();
                    endTime.setTime(sysRole.getNextTime());
                    endTime.add(Calendar.HOUR, sysRole.getCycle().intValue());
                    sysRole.setNextTime(endTime.getTime());
                    sysRoleMapper.updateRole(sysRole);

                    // 插入消息通知

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            taskExtractFlag = true;
        }
    }

    /**
     * 更新设备状态
     */
    public void updateEquipStatus() {
        try {
            if (!updateEquipmentFlag) {
                // 等待上次程序执行完毕
                return;
            }
            updateEquipmentFlag = false;
            List<EmEquipOperLog> emEquipOperLogs = taskMapper.selectEmAppointmentList();
            if (emEquipOperLogs.size() > 0) {
                for (EmEquipOperLog emEquipOperLog : emEquipOperLogs) {
                    emEquipOperLog.setStatus("1".equals(emEquipOperLog.getStatus()) ? "0" : "1");
                    // 记录操作日志
                    taskMapper.saveEquipOperLog(emEquipOperLog);
                    // 更新设备状态
                    taskMapper.updateEquipAppointment(emEquipOperLog);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            updateEquipmentFlag = true;
        }
    }


    /**
     * @param
     * @Description: 问题65 三片 28号被动抽查提醒  0 30 14 28 * ? *
     * @return: void
     * @Author: 唐子越
     * @Date: 2023/7/14 13:30
     */
    public void taskRemind() {

        try {

            // 阻止并发执行
            if (!taskRemindFlag) {
                return;
            }
            taskRemindFlag = false;


            //三片所有员工
            List<SysDept> sysDepts = sysDeptMapper.selectChildrenDeptById(270L);
            SysDept dept = new SysDept();
            dept.setDeptId(270L);
            sysDepts.add(dept);

            List<SysUser> users = sysDepts.stream().map(dep -> userMapper.selectUsernamesByDeptId(dep.getDeptId()))
                    .flatMap(Collection::stream).collect(Collectors.toList());


            //获得当前员工当周的任务列表
            users.forEach(user -> {

                Integer integer = emOutgoingQualityMapper.countUncompletedTaskByUserId(user.getUserId());
                //当周还有
                if (integer != 0) {
                    //提醒该用户
                    EmployeeWechat wechat = employeeWechatserMapper.selectEmployeeWechatById(user.getUserId().toString());
                    SendWeChatMessage.sendWeChatMessage(wechat.getUserid(), "", "", "本周还有未完成的被动抽查任务，请尽快完成", "0", "提醒");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            taskRemindFlag = true;
        }
    }

    /**
     * 记录白班次设备状态
     */
    public void insertEquipStatusLogA() {
        try {
            if (!insertEquipmentStatusFlag) {
                // 等待上次程序执行完毕
                return;
            }
            insertEquipmentStatusFlag = false;
            // 查询当前设备状态数据
            List<EquipStatusLog> equips = taskMapper.queryEquipStatus();
            for (EquipStatusLog log : equips) {
                log.setShiftType("0");
                taskMapper.saveEquipStatusLog(log);
            }

            // 更新工艺点检上班次未完成任务
            taskMapper.updateTechTaskOnShiftChange();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            insertEquipmentStatusFlag = true;
        }
    }

    /**
     * 记录夜班次设备状态
     */
    public void insertEquipStatusLogB() {
        try {
            if (!insertEquipmentStatusFlag) {
                // 等待上次程序执行完毕
                return;
            }
            insertEquipmentStatusFlag = false;
            // 查询当前设备状态数据
            List<EquipStatusLog> equips = taskMapper.queryEquipStatus();
            for (EquipStatusLog log : equips) {
                log.setShiftType("1");
                taskMapper.saveEquipStatusLog(log);
            }
            // 更新工艺点检上班次未完成任务
            taskMapper.updateTechTaskOnShiftChange();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            insertEquipmentStatusFlag = true;
        }
    }

    /**
     * 超时响应消息生成
     */
    public void overTimeMsg() {
        try {
            if (!overTimeMsgFlag) {
                // 等待上次程序执行完毕
                return;
            }
            overTimeMsgFlag = false;
            // 查询超时呼叫数据
            List<CallRecordInfoStic> callInfos = callRecordInfoMapper.queryOverTimeCallInfo();
            if (callInfos.size() > 0) {
                for (CallRecordInfoStic callInfo : callInfos) {
                    // 判断是否已推送过
                    if (StringUtils.isNull(callInfo.getNotingUser())) {
                        // 插入推送消息
                        MsgInfo msgInfo = new MsgInfo();
                        msgInfo.setEqKey(callInfo.getEqKey());
                        msgInfo.setIsRead("1");
                        msgInfo.setNewsDesc("资源呼叫[" + callInfo.getCallReason() + "],响应已超时，请核查");
                        msgInfo.setNewsType("资源呼叫[" + callInfo.getCallReason() + "]");
                        msgInfo.setNotingUser(callInfo.getUserName());
                        msgInfo.setSendUser(callInfo.getCallUser());
                        msgInfo.setSiteKey(callInfo.getSiteKey());
                        msgInfo.setRelationId(callInfo.getId());
                        // 插入信息
                        msgMapper.insertNewsRecord(msgInfo);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            overTimeMsgFlag = true;
        }

    }

    /**
     * 计划任务生成
     */
    public void createPlanAndTask() {
        try {
            if (!createPlanAndTaskFlag) {
                // 等待上次程序执行完毕
                return;
            }
            createPlanAndTaskFlag = false;

            // 查询到期未完成的任务，更新状态为系统标记完成
            taskMapper.updateTaskFinishOverSystem();

            // 更新所有未启用计划下次执行时间
            taskMapper.updateAllPlanTimeTask();
            // 查询计划任务
            List<EmPlanInfo> planTaskInfos = taskMapper.queryPlanTaskInfo();
            // 在类级别定义（用于存储每个site对应的角色列表）
            Map<Long, List<String>> siteDeptMap = new HashMap<>();
            if (planTaskInfos.size() > 0) {
                log.info("=======本次计划：{}条开始执行=========", planTaskInfos.size());
                for (EmPlanInfo planTaskInfo : planTaskInfos) {
                    planTaskInfoExecute = planTaskInfo;
                    //System.out.println("=======当前执行计划："+planTaskInfoExecute.getPlanCode());
                    String hangameKey = planTaskInfo.getHangameKey();
                    String planCode = planTaskInfo.getPlanCode();
                    String planName = planTaskInfo.getPlanName();
                    String site = planTaskInfo.getSiteKey();
                    String eqName = planTaskInfo.getEqKey();
                    String eqStatus = planTaskInfo.getEqStatus();
                    String department = planTaskInfo.getDepartment();
                    Long cycle = planTaskInfo.getCycle();
                    String startTime = planTaskInfo.getPlanStartTime();
                    String endTime = planTaskInfo.getPlanEndTime();
                    String nextTime = planTaskInfo.getNextExecuteTime();
                    String type = planTaskInfo.getPlanType();
                    String category = planTaskInfo.getPlanCategory();
                    String isRepeat = planTaskInfo.getIsRepeat();
                    String status = planTaskInfo.getStatus();
                    String eid = planTaskInfo.getEid();
                    Long id = planTaskInfo.getId();
                    String target = planTaskInfo.getTarget();
                    String estatus = planTaskInfo.getEstatus();
                    String model = planTaskInfo.getModel();

                    if (isRepeat != null && "0".equals(isRepeat)) {
                        target = "1";
                    } else {
                        target = "0";
                    }
                    planTaskInfo.setTarget(target);
                    // 判断计划类型
                    if (type == null || "".equals(type)) {
                        continue;
                    }
                    switch (type) {
                        case "0":
                            // 日任务
                            if ("0".equals(estatus)) {
                                // 设备状态为停机，日任务不生成,但更新下次执行时间
                                taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                continue;
                            } else {

                            }
                            break;
                        case "1":
                            // 周任务
                            if ("0".equals(estatus)) {
//							if (planTaskInfo.getPlanName().contains("工艺周任务") || planTaskInfo.getPlanName().contains("周工艺任务")){
//								//taskMapper.updatePlanTimeTaskByIdDay(planTaskInfo);
//								continue;
//							}
//							else {
                                // 设备状态为停机，周任务不生成,但更新下次执行时间
                                taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                continue;
//							}
                            }
                            break;
                        case "3":
                            if ("0".equals(estatus)) {
//							if (planTaskInfo.getPlanName().contains("工艺周任务") || planTaskInfo.getPlanName().contains("周工艺任务")){
//								//taskMapper.updatePlanTimeTaskByIdDay(planTaskInfo);
//								continue;
//							}
//							else {
                                // 设备状态为停机，周任务不生成,但更新下次执行时间
                                taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                continue;
//							}
                            }
                            break;
                        default:
                            // 判断设备状态与计划中设备状态一致
//						if (estatus == null || "".equals(estatus)) {
//							continue;
//						} else if (!estatus.equals(eqStatus)) {
//							continue;
//						}
//						break;
                    }

                    // 判断当前时间、 开始时间与结束时间等关系
                    if (startTime != null && endTime != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String sDate = sdf.format(new Date());
                        Date nowDate = null;
                        Date startTime1 = null;
                        Date endTime1 = null;
                        Date nextTime1 = null;

                        try {
                            nowDate = sdf.parse(sDate);
                            startTime1 = sdf.parse(startTime);
                            endTime1 = sdf.parse(endTime);
                            nextTime1 = sdf.parse(nextTime);

                            // ，判断下次执行时间+周期是否到当班时间
                            // 生成下次执行时间
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(nextTime1);
                            rightNow.add(Calendar.HOUR, Integer.valueOf(String.valueOf(cycle)));
                            Date dt1 = rightNow.getTime();

                            Calendar currentDayTime = Calendar.getInstance();

                            // 如果是日任务
                            if (type.equals("0")) {
                                currentDayTime.setTime(new Date());
                                Date currentDay = currentDayTime.getTime();
                                if (!dt1.after(currentDay)) {
                                    // 如果周期时间执行后没到当天，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }

                                // 如果是周任务
                            } else if (type.equals("1")) {
                                currentDayTime.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                                Date currentDay = currentDayTime.getTime();
                                if (dt1.before(currentDay)) {
                                    // 如果周期时间执行后没到当周，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }
                                // 如果是月任务
                            } else if (type.equals("2")) {
                                currentDayTime.set(Calendar.DAY_OF_MONTH, 1);
                                Date currentDay = currentDayTime.getTime();
                                if (dt1.before(currentDay)) {
                                    // 如果周期时间执行后没到当月，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }
                            }
                            // 如果是工艺任务
                            else if (type.equals("3")) {
                                currentDayTime.setTime(new Date());
                                Date currentDay = currentDayTime.getTime();
                                if (dt1.before(currentDay)) {
                                    // 如果周期时间执行后没到当天，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }
                            }


                        } catch (ParseException e) {

                        }
                        // 输入时间和当前时间一样； 返回值0
                        // 输入时间大于当前时间； 返回值1
                        // 输入时间小于当前时间； 返回值-1
                        if (startTime1.compareTo(nowDate) != 1 && endTime1.compareTo(nowDate) != -1
                                && nextTime1.compareTo(nowDate) < 0) {
                            // 查询设备操作时间周期内是否已有任务
                            Integer res = taskMapper.queryEquipOperTime(planTaskInfo);
                            if (res != null && res.intValue() == 1) {
                                // 生成下次执行时间
                                taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                continue;
                            }

                            // 统计未完成任务，发送给统计组
                            List<TaskInfo> tasks = taskMapper.selectEquipNofinishTask(Long.valueOf(eid));
                            if (tasks.size() > 0) {
                                // 插入通知消息
                                for (TaskInfo taskInfo : tasks) {
                                    MsgInfo msgInfo = new MsgInfo();
                                    msgInfo.setEqKey(Long.valueOf(eid));
                                    msgInfo.setNewsDesc(
                                            "设备[" + eqName + "],正生成新任务;\n存在[" + taskInfo.getTaskNum() + "]条任务未完成，请核查");
                                    msgInfo.setNewsType("设备任务统计");
                                    msgInfo.setNotingUser(taskInfo.getUserName());
                                    msgInfo.setSendUser("admin");
                                    msgInfo.setSiteKey(taskInfo.getSiteKey());
                                    // 插入信息
                                    msgMapper.insertNewsRecord(msgInfo);
                                }
                            }

                            // 获取序列号
                            SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
                            String code = SerialNumberUtil.getSerialNumber(BusinessConstants.PLAN_TASK,
                                    serial.getNextValue(), serial.getToday());
                            // 新增task
                            TaskInfo task = new TaskInfo();
                            task.setHangameKey(hangameKey);
                            task.setTaskCode(code);
                            task.setEqKey(Long.valueOf(eid));
                            task.setTaskType(type);
                            task.setTaskCategory(category);
                            task.setStatus("0");
                            task.setDepartment(department);
                            task.setSiteKey(Long.valueOf(site));
                            task.setEqStatus(eqStatus);
                            task.setPlanId(String.valueOf(id));
                            taskMapper.saveTask(task);
                            // 判断是否生成的是月任务
                            if (type.equals("2")) {
                                // 获取或创建该site的部门列表
                                List<String> deptList = siteDeptMap.getOrDefault(Long.valueOf(site), new ArrayList<>());
                                // 添加部门，确保不重复
                                if (!deptList.contains(department)) {
                                    deptList.add(department);
                                }
                            siteDeptMap.put(Long.valueOf(site), deptList);
                            }
                            // 查询点检项消息
                            EquipTaskItemInfo job = new EquipTaskItemInfo();
                            job.setModel(model);
                            if (!type.equals("2")) {
                                // 月任务不校验设备状态
                                job.setStatus(eqStatus);
                            }
                            job.setCycle(Integer.parseInt(cycle.toString()));
                            job.setItemType(type);
                            job.setDepartment(department);
                            job.setEqKey(eqName);
                            List<EquipTaskItemInfo> queryJobInfos = taskMapper.queryJobInfo(job);
                            int i = 0;
                            if (queryJobInfos.size() > 0) {
                                for (EquipTaskItemInfo queryJobInfo : queryJobInfos) {
                                    // 根据点检项消息生成taskItem
                                    i++;
                                    TaskItemInfo itemInfo = new TaskItemInfo();
                                    itemInfo.setSiteKey(queryJobInfo.getSiteKey());
                                    itemInfo.setTaskKey(code);
                                    itemInfo.setItemCode(queryJobInfo.getItemCode());
                                    itemInfo.setItemName(queryJobInfo.getItemName());
                                    itemInfo.setItemDesc(queryJobInfo.getItemDesc());
                                    itemInfo.setItemType(queryJobInfo.getCategory());
                                    itemInfo.setExecuteMeans(queryJobInfo.getExecuteMeans());
                                    itemInfo.setOrderNum(i);
                                    itemInfo.setFilePath(queryJobInfo.getFilePath());
                                    taskMapper.saveTaskItem(itemInfo);

                                    // 点检项id 查询具体的选项任务
                                    Long jobId = queryJobInfo.getId();
                                    EmItemFileInfo fileInfo = new EmItemFileInfo();
                                    fileInfo.setItemId(jobId);
                                    List<EmItemFileInfo> selectEmItemFileLists = taskMapper
                                            .selectEmItemFileList(fileInfo);
                                    // 点检选项任务
                                    if (selectEmItemFileLists.size() > 0) {
                                        // 查询最新taskItem的ID信息
                                        Long itemId = taskMapper.queryTaskItemId().getId();
                                        for (EmItemFileInfo selectEmItemFileList : selectEmItemFileLists) {
                                            // 填充选项任务
                                            TaskSelectInfo taskSelectInfo = new TaskSelectInfo();
                                            taskSelectInfo.setItemId(itemId);
                                            taskSelectInfo.setSelectCode(selectEmItemFileList.getSelectCode());
                                            taskSelectInfo.setSelectDesc(selectEmItemFileList.getSelectDesc());
                                            taskSelectInfo.setFilePath(selectEmItemFileList.getFilePath());
                                            taskSelectInfo.setJobSelectId(selectEmItemFileList.getId());
                                            taskMapper.insertTaskSelect(taskSelectInfo);
                                        }
                                    }
                                }
                            }

                            // 生成下次执行时间
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(nextTime1);
                            rightNow.add(Calendar.HOUR, Integer.valueOf(String.valueOf(cycle)));
                            Date dt1 = rightNow.getTime();
                            String oneHoursAgoTime = sdf.format(dt1);
                            planTaskInfo.setNextExecuteTime(oneHoursAgoTime);
                            planTaskInfo.setTarget(target);
                            // 计划是否重复执行判断
                            if (target != null && "1".equals(target)) {
                                // 不重复的计划，执行后更新计划状态为停用
                                planTaskInfo.setStatus("0");
                            }
                            taskMapper.updatePlanTask(planTaskInfo);
                        }
                    }
                }
            }
            // 在需要发送消息的地方（任务生成完成后）
            for (Map.Entry<Long, List<String>> entry : siteDeptMap.entrySet()) {
                Long siteId = entry.getKey();
                List<String> deptList = entry.getValue();
                if (!deptList.isEmpty()) {
                    log.info("开始处理站点: {}, 部门数量: {}", siteId, deptList.size());
                    List<EmployeeWechat> employeeList = employeeWechatserMapper.selectEmployeeWechatListByDept(deptList, siteId);
                    log.info("站点: {} 找到 {} 个需要通知的员工", siteId, employeeList.size());
                    int successCount = 0;
                    for (EmployeeWechat employeeWechat : employeeList) {
                        try {
                            SendWeChatMessage.sendWeChatMessage(
                                    employeeWechat.getUserid(),
                                    "",
                                    "",
                                    "月度任务已生成，请登录APP查看月度任务",
                                    "0",
                                    "月任务"
                            );
                            successCount++;
                        } catch (Exception e) {
                            log.error("发送微信消息失败，用户: {}", employeeWechat.getUserid(), e);
                        }
                    }
                    log.info("站点: {} 成功发送 {} 条消息", siteId, successCount);
                    deptList.clear();
                }
            }
            //新增维修计划
        } catch (Exception e) {
            e.printStackTrace();
            if (planTaskInfoExecute != null) {
                System.out.println("=======计划：" + planTaskInfoExecute.getPlanCode() + "异常,已重置该计划状态");
                planTaskInfoExecute.setStatus("0");
                taskMapper.updatePlanTask(planTaskInfoExecute);
            }
        } finally {
            // 置位
            createPlanAndTaskFlag = true;
            planTaskInfoExecute = null;
        }

    }

    /**
     * list去重
     */
    public static List<String> removeDuplicate(List<String> list) {
        HashSet<String> temp = new HashSet<>(list);
        list.clear();
        list.addAll(temp);
        return list;
    }

    /**
     * 工艺周任务点检任务定时生成
     */
    public void createPlanAndTaskProcess() {
        try {
            if (!createPlanAndTaskFlag) {
                // 等待上次程序执行完毕
                return;
            }
            createPlanAndTaskFlag = false;

            // 查询到期未完成的任务，更新状态为系统标记完成
            taskMapper.updateTaskFinishOverSystem();

            // 更新所有未启用计划下次执行时间
            taskMapper.updateAllPlanTimeTask();


            // 查询计划任务
            List<EmPlanInfo> planTaskInfos = taskMapper.queryPlanTaskInfoProcess();
            if (planTaskInfos.size() > 0) {
                //System.out.println("=======本次计划："+planTaskInfos.size()+"条开始执行=========");
                for (EmPlanInfo planTaskInfo : planTaskInfos) {
                    planTaskInfoExecute = planTaskInfo;
                    //System.out.println("=======当前执行计划："+planTaskInfoExecute.getPlanCode());
                    String hangameKey = planTaskInfo.getHangameKey();
                    String planCode = planTaskInfo.getPlanCode();
                    String planName = planTaskInfo.getPlanName();
                    String site = planTaskInfo.getSiteKey();
                    String eqName = planTaskInfo.getEqKey();
                    String eqStatus = planTaskInfo.getEqStatus();
                    String department = planTaskInfo.getDepartment();
                    Long cycle = planTaskInfo.getCycle();
                    String startTime = planTaskInfo.getPlanStartTime();
                    String endTime = planTaskInfo.getPlanEndTime();
                    String nextTime = planTaskInfo.getNextExecuteTime();
                    String type = planTaskInfo.getPlanType();
                    String category = planTaskInfo.getPlanCategory();
                    String isRepeat = planTaskInfo.getIsRepeat();
                    String status = planTaskInfo.getStatus();
                    String eid = planTaskInfo.getEid();
                    Long id = planTaskInfo.getId();
                    String target = planTaskInfo.getTarget();
                    String estatus = planTaskInfo.getEstatus();
                    String model = planTaskInfo.getModel();

                    if (isRepeat != null && "0".equals(isRepeat)) {
                        target = "1";
                    } else {
                        target = "0";
                    }
                    planTaskInfo.setTarget(target);
                    // 判断计划类型
                    if (type == null || "".equals(type)) {
                        continue;
                    }
                    switch (type) {
                        case "0":
                            // 日任务
                            if ("0".equals(estatus)) {
                                // 设备状态为停机，日任务不生成,但更新下次执行时间
                                taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                continue;
                            } else {

                            }
                            break;
                        case "1":
                            // 周任务
                            if ("0".equals(estatus)) {
                                if (planTaskInfo.getPlanName().contains("工艺周任务") || planTaskInfo.getPlanName().contains("周工艺任务")) {
                                    taskMapper.updatePlanTimeTaskByIdDay(planTaskInfo);
                                    continue;
                                } else {
                                    // 设备状态为停机，周任务不生成,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }
                            }
                            break;
                        case "3":
                            continue;
                        default:
                            // 判断设备状态与计划中设备状态一致
//						if (estatus == null || "".equals(estatus)) {
//							continue;
//						} else if (!estatus.equals(eqStatus)) {
//							continue;
//						}
//						break;
                    }

                    // 判断当前时间、 开始时间与结束时间等关系
                    if (startTime != null && endTime != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String sDate = sdf.format(new Date());
                        Date nowDate = null;
                        Date startTime1 = null;
                        Date endTime1 = null;
                        Date nextTime1 = null;

                        try {
                            nowDate = sdf.parse(sDate);
                            startTime1 = sdf.parse(startTime);
                            endTime1 = sdf.parse(endTime);
                            nextTime1 = sdf.parse(nextTime);

                            // ，判断下次执行时间+周期是否到当班时间
                            // 生成下次执行时间
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(nextTime1);
                            rightNow.add(Calendar.HOUR, Integer.valueOf(String.valueOf(cycle)));
                            Date dt1 = rightNow.getTime();

                            Calendar currentDayTime = Calendar.getInstance();

                            // 如果是日任务
                            if (type.equals("0")) {
                                currentDayTime.setTime(new Date());
                                Date currentDay = currentDayTime.getTime();
                                if (!dt1.after(currentDay)) {
                                    // 如果周期时间执行后没到当天，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }

                                // 如果是周任务
                            } else if (type.equals("1")) {
                                currentDayTime.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                                Date currentDay = currentDayTime.getTime();
                                if (dt1.before(currentDay)) {
                                    // 如果周期时间执行后没到当周，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                    continue;
                                }
                                // 如果是月任务
                            } else if (type.equals("2")) {
                                currentDayTime.set(Calendar.DAY_OF_MONTH, 1);
                                Date currentDay = currentDayTime.getTime();
                                if (dt1.before(currentDay)) {
                                    // 如果周期时间执行后没到当月，不生成任务,但更新下次执行时间
                                    taskMapper.updatePlanTimeTaskById(planTaskInfo);
//									if (site.equals("291")){
//										List<EmployeeWechat>employeelist= employeeWechatserMapper.selectEmployeeWechatListByRole(department);
//										for (EmployeeWechat employeeWechat : employeelist) {
//											SendWeChatMessage.sendWeChatMessage(employeeWechat.getUserid(),"","","月度任务已生成，请登录APP查看月度任务","0","提醒");
//
//										}
//									}
                                    continue;
                                }
                            }

                        } catch (ParseException e) {

                        }
                        // 输入时间和当前时间一样； 返回值0
                        // 输入时间大于当前时间； 返回值1
                        // 输入时间小于当前时间； 返回值-1
                        if (startTime1.compareTo(nowDate) != 1 && endTime1.compareTo(nowDate) != -1
                                && nextTime1.compareTo(nowDate) < 0) {
                            // 查询设备操作时间周期内是否已有任务
                            Integer res = taskMapper.queryEquipOperTime(planTaskInfo);
                            if (res != null && res.intValue() == 1) {
                                // 生成下次执行时间
                                taskMapper.updatePlanTimeTaskById(planTaskInfo);
                                continue;
                            }

                            // 统计未完成任务，发送给统计组
                            List<TaskInfo> tasks = taskMapper.selectEquipNofinishTask(Long.valueOf(eid));
                            if (tasks.size() > 0) {
                                // 插入通知消息
                                for (TaskInfo taskInfo : tasks) {
                                    MsgInfo msgInfo = new MsgInfo();
                                    msgInfo.setEqKey(Long.valueOf(eid));
                                    msgInfo.setNewsDesc(
                                            "设备[" + eqName + "],正生成新任务;\n存在[" + taskInfo.getTaskNum() + "]条任务未完成，请核查");
                                    msgInfo.setNewsType("设备任务统计");
                                    msgInfo.setNotingUser(taskInfo.getUserName());
                                    msgInfo.setSendUser("admin");
                                    msgInfo.setSiteKey(taskInfo.getSiteKey());
                                    // 插入信息
                                    msgMapper.insertNewsRecord(msgInfo);
                                }
                            }

                            // 获取序列号
                            SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
                            String code = SerialNumberUtil.getSerialNumber(BusinessConstants.PLAN_TASK,
                                    serial.getNextValue(), serial.getToday());
                            // 新增task
                            TaskInfo task = new TaskInfo();
                            task.setHangameKey(hangameKey);
                            task.setTaskCode(code);
                            task.setEqKey(Long.valueOf(eid));
                            task.setTaskType(type);
                            task.setTaskCategory(category);
                            task.setStatus("0");
                            task.setDepartment(department);
                            task.setSiteKey(Long.valueOf(site));
                            task.setEqStatus(eqStatus);
//							task.setExecuter("admin");
                            task.setPlanId(String.valueOf(id));
                            taskMapper.saveTask(task);
                            // 查询点检项消息
                            EquipTaskItemInfo job = new EquipTaskItemInfo();
                            job.setModel(model);
                            if (!type.equals("2")) {
                                // 月任务不校验设备状态
                                job.setStatus(eqStatus);
                            }

                            job.setCycle(Integer.parseInt(cycle.toString()));
                            job.setItemType(type);
                            job.setDepartment(department);
                            job.setEqKey(eqName);
                            List<EquipTaskItemInfo> queryJobInfos = taskMapper.queryJobInfo(job);
                            int i = 0;
                            if (queryJobInfos.size() > 0) {
                                for (EquipTaskItemInfo queryJobInfo : queryJobInfos) {
                                    // 根据点检项消息生成taskItem
                                    i++;
                                    TaskItemInfo itemInfo = new TaskItemInfo();
                                    itemInfo.setSiteKey(queryJobInfo.getSiteKey());
                                    itemInfo.setTaskKey(code);
                                    itemInfo.setItemCode(queryJobInfo.getItemCode());
                                    itemInfo.setItemName(queryJobInfo.getItemName());
                                    itemInfo.setItemDesc(queryJobInfo.getItemDesc());
                                    itemInfo.setItemType(queryJobInfo.getCategory());
                                    itemInfo.setExecuteMeans(queryJobInfo.getExecuteMeans());
                                    itemInfo.setOrderNum(i);
                                    itemInfo.setFilePath(queryJobInfo.getFilePath());
                                    taskMapper.saveTaskItem(itemInfo);

                                    // 点检项id 查询具体的选项任务
                                    Long jobId = queryJobInfo.getId();
                                    EmItemFileInfo fileInfo = new EmItemFileInfo();
                                    fileInfo.setItemId(jobId);
                                    List<EmItemFileInfo> selectEmItemFileLists = taskMapper
                                            .selectEmItemFileList(fileInfo);
                                    // 点检选项任务
                                    if (selectEmItemFileLists.size() > 0) {
                                        // 查询最新taskItem的ID信息
                                        Long itemId = taskMapper.queryTaskItemId().getId();
                                        for (EmItemFileInfo selectEmItemFileList : selectEmItemFileLists) {
                                            // 填充选项任务
                                            TaskSelectInfo taskSelectInfo = new TaskSelectInfo();
                                            taskSelectInfo.setItemId(itemId);
                                            taskSelectInfo.setSelectCode(selectEmItemFileList.getSelectCode());
                                            taskSelectInfo.setSelectDesc(selectEmItemFileList.getSelectDesc());
                                            taskSelectInfo.setFilePath(selectEmItemFileList.getFilePath());
                                            taskSelectInfo.setJobSelectId(selectEmItemFileList.getId());
                                            taskMapper.insertTaskSelect(taskSelectInfo);
                                        }
                                    }
                                }
                            }

                            // 生成下次执行时间
                            Calendar rightNow = Calendar.getInstance();
                            rightNow.setTime(nextTime1);
                            rightNow.add(Calendar.HOUR, Integer.valueOf(String.valueOf(cycle)));
                            Date dt1 = rightNow.getTime();
                            String oneHoursAgoTime = sdf.format(dt1);
                            planTaskInfo.setNextExecuteTime(oneHoursAgoTime);
                            planTaskInfo.setTarget(target);
                            // 计划是否重复执行判断
                            if (target != null && "1".equals(target)) {
                                // 不重复的计划，执行后更新计划状态为停用
                                planTaskInfo.setStatus("0");
                            }
                            taskMapper.updatePlanTask(planTaskInfo);
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            if (planTaskInfoExecute != null) {
                System.out.println("=======计划：" + planTaskInfoExecute.getPlanCode() + "异常,已重置该计划状态");
                planTaskInfoExecute.setStatus("0");
                taskMapper.updatePlanTask(planTaskInfoExecute);
            }
        } finally {
            // 置位
            createPlanAndTaskFlag = true;
            planTaskInfoExecute = null;
        }

    }

    /**
     * 任务完成的情况统计
     */
    public void sumRepairAndTask() {
        try {
            if (!sumRepairAndTaskFlag) {
                // 等待上次程序执行完毕
                return;
            }
            sumRepairAndTaskFlag = false;

            // 查询任务工厂信息
            List<SiteTask> querySiteTasks = taskMsgMapper.querySiteTask();
            if (querySiteTasks.size() > 0) {
                for (SiteTask siteTask : querySiteTasks) {
                    Long siteKey = siteTask.getSiteKey();
                    // 查询任务
                    ReportTask taskInfo = new ReportTask();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sDate = sdf.format(new Date());

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    String zero = sdf.format(calendar.getTime());
                    taskInfo.setSiteKey(siteKey);
                    taskInfo.setStartTime(zero);
                    taskInfo.setEndTime(sDate);
                    // 获取任务的总量、完成量
                    List<ReportTask> taskInfoAll = taskMsgMapper.queryTaskInfoAll(taskInfo);
                    String message = "";
                    if (taskInfoAll.size() > 0) {
                        for (ReportTask taskList : taskInfoAll) {
                            message += (taskList.getTaskType() + ":总量为" + taskList.getTaskNum() + ",完成"
                                    + taskList.getFinishTaskNum() + ",未完成" + taskList.getUnFinishTaskNum() + "; ");
                        }
                    }
                    // 查询维修任务统计信息
                    ReportTask repairInfo = taskMsgMapper.queryRepairInfoAll(taskInfo);
                    if (repairInfo != null) {
                        message += ("维修统计:总量为" + repairInfo.getTaskNum() + ",完成" + repairInfo.getFinishTaskNum() + ";");
                    }
                    // 查询工厂查询人员信息
                    SiteTask userInfo = new SiteTask();
                    userInfo.setSiteKey(siteKey);
                    List<SiteTask> userTaskList = taskMsgMapper.queryUserTask(userInfo);
                    if (userTaskList.size() > 0) {
                        for (SiteTask userList : userTaskList) {
                            String user = userList.getUserName();
                            MsgInfo info = new MsgInfo();
                            info.setNewsDesc(message);
                            info.setNewsType("统计完成进度");
                            info.setSiteKey(siteKey);
                            info.setSendUser(user);
                            taskMsgMapper.insertTaskRecord(info);
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            sumRepairAndTaskFlag = true;
        }

    }

    /**
     * 更新超时打开用户状态
     */
    public void updateUserClockInStatus() {

        try {
            if (!updateUserClockInStatusFlag) {
                // 等待上次程序执行完毕
                return;
            }
            updateUserClockInStatusFlag = false;

            // 查询超时用户
            List<UserClockInLog> userClockInLogs = sysJobMapper.selectUserLog();
            if (userClockInLogs.size() > 0) {
                // 更新用户打卡状态
                sysJobMapper.updateUserClockin();
                for (UserClockInLog userClockInLog : userClockInLogs) {
                    userClockInLog.setCurrentStatus("1");
                    userClockInLog.setUpdatedStatus("0");
                    userClockInLog.setOperationType("1");
                    sysJobMapper.insertUserClockInLog(userClockInLog);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 置位
            updateUserClockInStatusFlag = true;
        }

    }

    /**
     * 太仓工厂验收关闭提醒功能
     */
    public void overdueReminder() {

    }

    public void sendwecomcalc() {
        //每周推送一次
        SendWeChatMessage sc = new SendWeChatMessage();
        //获取任务点检项明细,三级以上任务项
        List<EmJobItem> list = emJobItemService.selectEmJobItemListLPA();
        //  List<String> attendlist= new List<String>();
        //  attendlist.add("")
        //	attendlist = sc.sendWechattoschedule("LiZhao",);
    }

    /**
     * 极光推送
     *
     * @param msgInfo
     */
    @SuppressWarnings("static-access")
    public void jpushMsg(MsgInfo msgInfo) {
        try {
            if (StringUtils.isEmpty(msgInfo.getNotingUser()) || StringUtils.isEmpty(msgInfo.getNewsDesc())) {
                msgMapper.updateMsgPushStatus(msgInfo);
                return;
            }
            // 推送
            if ("@all".equals(msgInfo.getNotingUser())) {
                // 查询当前工厂在线用户
                SysUser sysUser = new SysUser();
                sysUser.setSite(msgInfo.getSiteKey());
                List<SysUser> userList = sysUserMapper.selectUserListBySite(sysUser);
                if (userList.size() > 0) {
                    for (int i = 0; i < userList.size(); i++) {
                        alias[0] = userList.get(i).getUserName();
                        try {
                            //安卓
                            pushResult = jpushUtils.sendCustomPush(msgInfo.getNewsType(), msgInfo.getNewsDesc(), map, alias);
                            //ios
                            jpushUtils.jpushIOS(msgInfo.getNewsType(), msgInfo.getNewsDesc(), map, alias);
                        } catch (Exception e) {
                            continue;
                        }

                    }
                }
            } else {
                alias[0] = msgInfo.getNotingUser();
                //安卓
                pushResult = jpushUtils.sendCustomPush(msgInfo.getNewsType(), msgInfo.getNewsDesc(), map, alias);
                //ios
                jpushUtils.jpushIOS(msgInfo.getNewsType(), msgInfo.getNewsDesc(), map, alias);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    public void test() {
        List<EmployeeWechat> employeelist = employeeWechatserMapper.selectEmployeeWechatListByRole("");
        for (EmployeeWechat employeeWechat : employeelist) {
            SendWeChatMessage.sendWeChatMessage(employeeWechat.getUserid(), "", "", "月度任务已生成，请登录APP查看月度任务", "0", "提醒");

        }
    }

    /**
     * 塑胶事业部JIT送货工作任务管理推送消息功能
     */
    public void SendJITLogisticsTimeoutMessages() {
        //正常提醒
        //检索集货超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList1 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut();
        //检索车辆到厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList2 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut();
        //检索车辆离厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList3 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut();


        List<ProductionDeliveryPlan> productionDeliveryPlanList11 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut4();
        //检索车辆到厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList21 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut4();
        //检索车辆离厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList31 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut4();

        String url1 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3ba33a38-d30c-4016-96f4-1ff54ffe0010";
        String urlall = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a8a9f53e-df4e-440d-9e49-3d17295c0b11";
        String urlhefei = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=282a0ba8-13ea-49ee-9b47-5bc6fce08e6e";
        String urlguangzhou = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ac923116-2155-4f20-9442-6495bf8a04a8";
        //发小群
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList1) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), url1);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }
        //大群
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList11) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlall);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList2) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), url1);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList21) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlall);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList3) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), url1);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList31) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlall);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }


        //检索普通延迟信息,发完消息将1->3
        List<ProductionDeliveryPlan> productionDeliveryPlanList4 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut1();
        List<ProductionDeliveryPlan> productionDeliveryPlanList5 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut1();
        List<ProductionDeliveryPlan> productionDeliveryPlanList6 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut1();


        String url2 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3ba33a38-d30c-4016-96f4-1ff54ffe0010";
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList4) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delay(arg.delay1(sysDept.getDeptName()), url2);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut1(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delay(arg.delay1(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut1(arg.getId());
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delay(arg.delay1(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut1(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList5) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delay(arg.delay2(sysDept.getDeptName()), url2);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delay(arg.delay2(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delay(arg.delay2(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut1(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList6) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delay(arg.delay3(sysDept.getDeptName()), url2);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delay(arg.delay3(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delay(arg.delay3(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut1(arg.getId());
            }
        }


        String url3 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a8a9f53e-df4e-440d-9e49-3d17295c0b11";
        //检索超级延迟信息,发完消息将2->4
        List<ProductionDeliveryPlan> productionDeliveryPlanList7 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut2();
        List<ProductionDeliveryPlan> productionDeliveryPlanList8 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut2();
        List<ProductionDeliveryPlan> productionDeliveryPlanList9 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut2();

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList7) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delaysuper(arg.delaysuper1(sysDept.getDeptName()), url3);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delaysuper(arg.delaysuper1(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delaysuper(arg.delaysuper1(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut2(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList8) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delaysuper(arg.delaysuper2(sysDept.getDeptName()), url3);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delaysuper(arg.delaysuper2(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut2(arg.getId());
            }

            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delaysuper(arg.delaysuper2(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut2(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList9) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delaysuper(arg.delaysuper3(sysDept.getDeptName()), url3);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delaysuper(arg.delaysuper3(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delaysuper(arg.delaysuper3(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut2(arg.getId());
            }
        }
    }

    @Test
    public void test123() {
        List<ProductionDeliveryPlan> productionDeliveryPlanList1 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut();
        //检索车辆到厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList2 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut();
        //检索车辆离厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList3 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut();


        List<ProductionDeliveryPlan> productionDeliveryPlanList11 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut4();
        //检索车辆到厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList21 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut4();
        //检索车辆离厂超时
        List<ProductionDeliveryPlan> productionDeliveryPlanList31 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut4();

        String url1 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3ba33a38-d30c-4016-96f4-1ff54ffe0010";
        String urlall = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a8a9f53e-df4e-440d-9e49-3d17295c0b11";
        String urlhefei = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=282a0ba8-13ea-49ee-9b47-5bc6fce08e6e";
        String urlguangzhou = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ac923116-2155-4f20-9442-6495bf8a04a8";
        //发小群
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList1) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), url1);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }
        //大群
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList11) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlall);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1(arg.shippingconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList2) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), url1);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList21) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlall);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2(arg.vehiclearrivesconfirmTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList3) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), url1);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList31) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlall);
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlhefei);
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3(arg.departureconfirmationTimeOuttoString(sysDept.getDeptName()), urlguangzhou);
            }
        }


        //检索普通延迟信息,发完消息将1->3
        List<ProductionDeliveryPlan> productionDeliveryPlanList4 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut1();
        List<ProductionDeliveryPlan> productionDeliveryPlanList5 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut1();
        List<ProductionDeliveryPlan> productionDeliveryPlanList6 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut1();


        String url2 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=3ba33a38-d30c-4016-96f4-1ff54ffe0010";
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList4) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delay(arg.delay1(sysDept.getDeptName()), url2);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut1(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delay(arg.delay1(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut1(arg.getId());
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delay(arg.delay1(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut1(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList5) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delay(arg.delay2(sysDept.getDeptName()), url2);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delay(arg.delay2(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delay(arg.delay2(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut1(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList6) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delay(arg.delay3(sysDept.getDeptName()), url2);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delay(arg.delay3(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut1(arg.getId());
            }

            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delay(arg.delay3(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut1(arg.getId());
            }
        }


        String url3 = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=a8a9f53e-df4e-440d-9e49-3d17295c0b11";
        //检索超级延迟信息,发完消息将2->4
        List<ProductionDeliveryPlan> productionDeliveryPlanList7 = productionDeliveryPlanMapper.selectshippingconfirmationTimeOut2();
        List<ProductionDeliveryPlan> productionDeliveryPlanList8 = productionDeliveryPlanMapper.selectdepartureconfirmationTimeOut2();
        List<ProductionDeliveryPlan> productionDeliveryPlanList9 = productionDeliveryPlanMapper.selectvehiclearrivesconfirmTimeOut2();

        for (ProductionDeliveryPlan arg : productionDeliveryPlanList7) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delaysuper(arg.delaysuper1(sysDept.getDeptName()), url3);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delaysuper(arg.delaysuper1(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS1delaysuper(arg.delaysuper1(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updateshippingconfirmationTimeOut2(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList8) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delaysuper(arg.delaysuper2(sysDept.getDeptName()), url3);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delaysuper(arg.delaysuper2(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut2(arg.getId());
            }

            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS2delaysuper(arg.delaysuper2(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatedepartureconfirmationTimeOut2(arg.getId());
            }
        }
        for (ProductionDeliveryPlan arg : productionDeliveryPlanList9) {
            SysDept sysDept = sysDeptMapper.selectDeptById(Convert.toLong(arg.getFactoryid()));
            if (arg.getFactoryid().equals("253")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delaysuper(arg.delaysuper3(sysDept.getDeptName()), url3);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("623")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delaysuper(arg.delaysuper3(sysDept.getDeptName()), urlhefei);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut2(arg.getId());
            }
            if (arg.getFactoryid().equals("240")) {
                SendWeChatMessage.JITsendWeChatMessageToS3delaysuper(arg.delaysuper3(sysDept.getDeptName()), urlguangzhou);
                productionDeliveryPlanMapper.updatevehiclearrivesconfirmTimeOut2(arg.getId());
            }
        }
    }

    public void Sendrepairmessage() {
        //2小时无接单提醒
        List<RequestInfo> requestInfos = resquestInfoService.selectCheckedListOverTime();
        for (RequestInfo arg : requestInfos) {
            String robotUrl = null;
            SysDictData dictData = new SysDictData();
            dictData.setDictType("robotUrl");
            SysDept sysDept = sysDeptMapper.selectDeptById(arg.getSiteKey());
            dictData.setDictLabel(sysDept.getDeptName());
            List<SysDictData> list = dictDataMapper.selectDictDataList(dictData);
            EmEquip emEquip = emEqualTo.selectEmEquipById(arg.getEqKey());
            SysUser sysUser = userMapper.selectUserByUserName(arg.getRequestUser());
            if (list.size() > 0) {
                if (emEquip != null) {
                    robotUrl = list.get(0).getDictValue();
                    SendWeChatMessage.sendWeChatMessageToAll(arg.toOverTimeString(emEquip.getName(), emEquip.getDesc(), sysUser.getNickName()), "两小时无接单", robotUrl);
                    resquestInfoService.updateCheckedListOverTime(arg.getId());
                }
            }
        }
        //2小时未验收提醒
        List<RepairRecordInfo> repairRecordInfoList = repairRecordInfoService.selectRepairByRequestOverTime();
        if (!repairRecordInfoList.isEmpty()) {
            for (RepairRecordInfo arg : repairRecordInfoList) {
                String robotUrl = null;
                SysDictData dictData = new SysDictData();
                dictData.setDictType("robotUrl");
                SysDept sysDept = sysDeptMapper.selectDeptById(arg.getSiteKey());
                dictData.setDictLabel(sysDept.getDeptName());
                List<SysDictData> list = dictDataMapper.selectDictDataList(dictData);
                if (list.size() > 0) {
                    robotUrl = list.get(0).getDictValue();
                    SendWeChatMessage.sendWeChatMessageToAll(arg.toOverTime(), "两小时未确认", robotUrl);
                    repairRecordInfoService.updateRepairByRequestOverTime(arg.getId());
                }
            }
        }
    }

}
